#include "timer_manager.h"
#include "elog.h"
#include "elog_file.h"

#include <event2/event.h>
#include <event2/event_struct.h>

TimerManager::TimerManager() : base_(event_base_new()), timer_(nullptr), timer_seconds_(0), running_(false) {}

TimerManager::~TimerManager() {
    stopTimer(); // 停止定时器
    event_base_loopbreak(base_); // 停止事件循环
    event_base_free(base_);
}

void TimerManager::startTimer(std::function<void(int)> callback, int seconds) {
    callback_ = callback;
    timer_seconds_ = seconds;
    run_count_ = -1; // 设置为负数表示无限运行

    if (!running_) {
        struct timeval tv;
        tv.tv_sec = seconds;
        tv.tv_usec = 0;
        timer_ = event_new(base_, -1, EV_PERSIST, timerCallback, this);
        event_add(timer_, &tv);
        clock_gettime(CLOCK_MONOTONIC, &start_time_);
        running_ = true;
        eventThread_ = std::thread(&TimerManager::runEventLoop, this);
        eventThread_.detach();
    }
}

void TimerManager::startTimer(std::function<void(int)> callback, int seconds, int run_count) {
    callback_ = callback;
    timer_seconds_ = seconds;
    run_count_ = run_count;

    if (!running_) {
        struct timeval tv;
        tv.tv_sec = seconds;
        tv.tv_usec = 0;
        timer_ = event_new(base_, -1, EV_PERSIST, timerCallback, this);
        event_add(timer_, &tv);
        clock_gettime(CLOCK_MONOTONIC, &start_time_);
        running_ = true;
        eventThread_ = std::thread(&TimerManager::runEventLoop, this);
        eventThread_.detach();
    }
}

void TimerManager::stopTimer() {
    if (timer_) {
        event_del(timer_);
        event_free(timer_);
        timer_ = nullptr;
        running_ = false;
        event_base_loopbreak(base_); // 停止事件循环
    }
}

void TimerManager::timerCallback(evutil_socket_t fd, short events, void* arg) {
    TimerManager* timerManager = static_cast<TimerManager*>(arg);
    struct timespec current_time;
    clock_gettime(CLOCK_MONOTONIC, &current_time);
    int elapsed_time = static_cast<int>(current_time.tv_sec - timerManager->start_time_.tv_sec);
    timerManager->callback_(elapsed_time);

    if (timerManager->run_count_ != -1) { // 如果 run_count_ 不等于 -1，减小计数器的值
        timerManager->run_count_--;
        if (timerManager->run_count_ == 0) {
            timerManager->stopTimer();
        }
    }
}

void TimerManager::runEventLoop() {
    event_base_dispatch(base_);
}